package io.github.jesse205.dragdrop.pro.ui.settings

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams.MATCH_PARENT
import androidx.preference.PreferenceFragmentCompat
import com.google.android.material.appbar.AppBarLayout
import io.github.jesse205.dragdrop.pro.R
import io.github.jesse205.dragdrop.pro.app.AppPreference
import io.github.jesse205.dragdrop.pro.app.toThemeType
import io.github.jesse205.dragdrop.pro.databinding.FragmentSettingsBinding
import io.github.jesse205.dragdrop.pro.extensions.setupToolbar
import io.github.jesse205.dragdrop.pro.extensions.thisActivity
import rikka.preference.SimpleMenuPreference

class SettingsFragment : PreferenceFragmentCompat() {

    private var _binding: FragmentSettingsBinding? = null
    private val binding get() = _binding!!
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingsBinding.inflate(inflater, container, false)
        setupToolbar(binding.toolbar, thisActivity is SettingsActivity)

        val root = binding.root
        val child = super.onCreateView(inflater, container, savedInstanceState)
        val layoutParams = CoordinatorLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT).apply {
            behavior = AppBarLayout.ScrollingViewBehavior()
        }
        root.addView(child, layoutParams)
        return root
    }

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val themeTypePreference = findPreference<SimpleMenuPreference>(AppPreference.KEY_THEME_TYPE)
        themeTypePreference!!.setOnPreferenceChangeListener { _, newValue ->
            if (thisActivity.themeManager.isThemeChanged((newValue as String).toThemeType()))
                thisActivity.recreate()
            true
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}